<?php

namespace App\Http\Controllers\Admin;

use App\Http\Model\Article;
use App\Http\Model\Category;
use Illuminate\Http\Request;

use App\Http\Requests;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;

class ArticleController extends CommonController
{
    //  get: admin/article  全部文章列表
	public function index()
	{
		$data = Article::orderBy('article_id', 'desc')->paginate(5);
		return view('admin.article.index', compact('data'));
	}

	//  get: admin/article/create  添加文章列表
	public function create()
	{
		$categories = (new Category())->tree();
		return view('admin.article.create', compact('categories'));
	}

	//  post: admin/article
	public function store()
	{
		$input = Input::except('_token', 'fileselect');
		$input['article_time'] = time();
		$rules = [
			'article_title' => 'required',
			'article_content' => 'required'
		];
		$message = [
			'article_title.required' => '文章名称不能为空',
			'article_content.required' => '文章内容不能为空'
		];
		$validator = Validator::make($input, $rules, $message);

		if ($validator->passes()) {
			$result = Article::create($input);
			if ($result) {
				return redirect('admin/article');
			} else {
				$errors = array('数据填充失败，请稍后重试');
				return back()->withErrors($errors);
			}
		} else {
			return back()->withErrors($validator);
		}
	}

	//  get: admin/article/{article_id}/edit
	public function edit($article_id)
	{
		$categories = (new Category)->tree();
		$field = Article::find($article_id);
		return view('admin.article.edit', compact('categories', 'field'));
	}

	//  put: admin/article/{article_id}
	public function update($article_id)
	{
		$input = Input::except('_method', '_token', 'fileselect');
		$result = Article::where('article_id', $article_id)->update($input);
		if ($result) {
			return redirect('admin/article');
		} else {
			return back()->with('errors', '文章更新失败， 请稍后重试');
		}
	}

	//  delete: admin/article/{article}
	public function destroy($article_id)
	{
		$result = Article::where('article_id', $article_id)->delete();
		if ($result) {
			$data = [
				'status' => 0,
				'msg' => '文章删除成功'
			];
		} else {
			$data = [
				'status' => 1,
				'msg' => '文章删除失败，请稍后重试'
			];
		}
		return $data;
	}
}
